#!/bin/sh

start_service() {
    CURRENT_PATH=$1
    SERVICE_FILE=$2
    if [ ! -f ${CURRENT_PATH}/${SERVICE_FILE} ]; then
        logger_Error "Not found ${SERVICE_FILE}, please check"
        return 1
    fi

    if [ ! -d /lib/systemd/system ]; then
        logger_Error "Not found /lib/systemd/system"
        return 1
    fi

    if [ -f /lib/systemd/system/${SERVICE_FILE} ]; then
        sudo systemctl stop ${SERVICE_FILE}  >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            logger_Error "systemctl stop ${SERVICE_FILE} error, please check."
            return 1
        fi
        sudo systemctl disable ${SERVICE_FILE}  >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            logger_Warn "systemctl disable ${SERVICE_FILE} failed."
        fi
        sudo rm -f /lib/systemd/system/${SERVICE_FILE}
    fi

    if [ ! -f ${CURRENT_PATH}/${SERVICE_FILE} ]; then
        logger_Error "${SERVICE_FILE} not found, please check."
        return 1
    fi
    if [ ! -d /lib/systemd/system ]; then
        logger_Error "/lib/systemd/system not found, please check."
        return 1
    fi
    sudo cp -f ${CURRENT_PATH}/${SERVICE_FILE} /lib/systemd/system
    sudo systemctl enable ${SERVICE_FILE}  >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        logger_Error "systemctl enable ${SERVICE_FILE} with error, please check."
        return 1
    fi
    sudo systemctl daemon-reload  >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        logger_Error "systemctl daemon-reload with error, please check."
        return 1
    fi
    sudo systemctl start ${SERVICE_FILE}  >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        logger_Error "systemctl start ${SERVICE_FILE} with error, please check."
        exit 1
    fi
}

stop_service() {
    SERVICE_FILE=$1
    if [ -f /lib/systemd/system/${SERVICE_FILE} ]; then
        sudo systemctl stop ${SERVICE_FILE}  >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            logger_Error "systemctl stop ${SERVICE_FILE} with error, please check."
            return 1
        fi

        sudo systemctl disable ${SERVICE_FILE}  >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            logger_Error "systemctl disable ${SERVICE_FILE} with error, please check."
            return 1
        fi
    fi
    if [ -f /lib/systemd/system/${SERVICE_FILE} ]; then
        sudo rm -f /lib/systemd/system/${SERVICE_FILE}
fi
}

stop_application()
{
    SERVICE_FILE=$1
    if [ -f /lib/systemd/system/${SERVICE_FILE} ]; then
        sudo systemctl stop ${SERVICE_FILE}  >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            logger_Error "systemctl stop ${SERVICE_FILE} with error, please check."
            return 1
        fi
    fi
}

is_upgrade_task() {
    current_task=`cat ${TASK} | grep "task" | cut -d":" -f2` || true

    if [ ! -z "${current_task+x}" ] && [ "${current_task}" = "upgrade" ]; then
        return 1
    else
        return 0
    fi
}

function DelINIfileItem(){
    INIFILE=$1
    SECTION=$2
    ITEM=$3
    sed -i "/^\[$SECTION\]/,/^\[/ {/$ITEM=/d}" $INIFILE
}

function ReadINIfile()
{
	INIFILE=$1
	SECTION=$2
	ITEM=$3 
	ReadINI=`awk -F '=' '/\['$SECTION'\]/{a=1}a==1&&$1~/'$ITEM'/{print $2;exit}' $INIFILE`
  	echo $ReadINI
}

function WriteINIfile(){
    INIFILE=$1
    SECTION=$2
    ITEM=$3
    NEWVAL=$4

    sed -n "/^\[$SECTION\]/,/^\[/p;" $INIFILE | grep ^$ITEM=
    if [ $? != 0 ]; then
        # no item info so new write one line
        logger_Info "write iniFile find no $ITEM so new write one line"
        WriteINI=`sed -i   "/^\[$SECTION\]/a $ITEM=$NEWVAL" $INIFILE`
    else
        WriteINI=`sed -i "/^\[$SECTION\]/,/^\[/ {/^\[$SECTION\]/b;/^\[/b;s#^$ITEM*=.*#$ITEM=$NEWVAL#g;}" $INIFILE`
    fi
}

readIniSections() {
    file=$1;
    val=$(awk '/\[/{printf("%s ",$1)}' ${file} | sed 's/\[//g' | sed 's/\]//g')
}

check_conflict_process() {
    check_process=$1
    local process_id=`ps -C $check_process | grep -v PID | awk '{print $1}'`
    if [ -z "${process_id+x}" ] || [ "${process_id}" = "" ]; then
        logger_Debug "Check conflict process ok. "${check_process} 
    else
        logger_Warn "check has comflict process:" ${check_process}
        return 1
    fi
}

function is_both_numeric() {
    [ -z "$1" ] && return 1
    [ -z "$2" ] && return 1
    [ -n "$(echo "$1" | sed 's/[0-9]//g')" ] && return 1
    [ -n "$(echo "$2" | sed 's/[0-9]//g')" ] && return 1
    return 0
}

# compare version $1 and $2; 0---equal, 1---greater, 2---smaller
function version_compare() {
    [ "$1" == "$2" ] && return 0
    local IFS=.
    ver1=($1)
    ver2=($2)

    [ ${#ver1[@]} -ge ${#ver2[@]} ] && max_ver_len=${#ver1[@]} || max_ver_len=${#ver2[@]}

    for ((i=0; i<$max_ver_len; i++)); do
        is_both_numeric "${ver1[$i]}" "${ver2[$i]}"
        if [ $? -eq 0 ]; then
            [ "${ver1[$i]}" -gt "${ver2[$i]}" ] && return 1
            [ "${ver1[$i]}" -lt "${ver2[$i]}" ] && return 2
        else
            [ "${ver1[$i]}" \> "${ver2[$i]}" ] && return 1
            [ "${ver1[$i]}" \< "${ver2[$i]}" ] && return 2
        fi
    done
    return 0
}

#check command exist or not
#       $1: command
function check_command_exist()
{
    command=$1
    if type $command >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

function set_file_link(){
    base_path=$1
    ln -sf ${base_path}/software/libs/libc-2.29.so ${base_path}/software/libs/libc.so.6
    ln -sf ${base_path}/software/libs/ld-2.29.so ${base_path}/software/libs/ld-linux-aarch64.so.1
    ln -sf ${base_path}/software/libs/libpthread-2.29.so ${base_path}/software/libs/libpthread.so
    ln -sf ${base_path}/software/libs/libpthread-2.29.so ${base_path}/software/libs/libpthread.so.0
    ln -sf ${base_path}/software/libs/libdl-2.29.so ${base_path}/software/libs/libdl.so.2
    ln -sf ${base_path}/software/libs/libdl-2.29.so ${base_path}/software/libs/libdl.so
    ln -sf ${base_path}/software/libs/libm-2.29.so ${base_path}/software/libs/libm.so
    ln -sf ${base_path}/software/libs/libm-2.29.so ${base_path}/software/libs/libm.so.6 

    ln -sf ${base_path}/software/libs/libssl.so.1.1 ${base_path}/software/libs/libssl.so
    ln -sf ${base_path}/software/libs/libssl.so.1.1 ${base_path}/software/libs/libssl.so.1.1.1
    ln -sf ${base_path}/software/libs/libcrypto.so.1.1 ${base_path}/software/libs/libcrypto.so
    ln -sf ${base_path}/software/libs/libcrypto.so.1.1 ${base_path}/software/libs/libcrypto.so.1.1.1

    ln -sf ${base_path}/software/libs/libmbedtls.so ${base_path}/software/lib/libmbedtls.so

    ln -sf ${base_path}/software/lib/libsecurec.so ${base_path}/software/libs/libsecurec.so
    ln -sf ${base_path}/software/lib/libkeymanage.so ${base_path}/software/libs/libkeymanage.so
    ln -sf ${base_path}/software/lib/liblogcommon.so ${base_path}/software/libs/liblogcommon.so
    ln -sf ${base_path}/software/lib/libcmscbb.so ${base_path}/software/libs/libcmscbb.so

    ln -sf ${base_path}/software/edge_site/edge_manager/config/default_capability.json ${base_path}/config/default_capability.json
}

check_command_list=(arping gzip mkdir touch reboot mv chmod rm docker sed wc ls find cat grep du awk openssl ip ifconfig ethtool cp systemctl  pidof mount umount ps getconf kill tar iptables systemd-run sync grep xargs expect inotifywait)

check_all_commands()
{
    for i in ${check_command_list[@]};
    do        
        check_command_exist $i
        if [ $? -ne 0 ]; then
            logger_Warn "check comand err $i no exist return"
            return 1
        fi
    done

    return 0
}

# clean config.ini inactive info
function clear_inactive_config_info(){
    DelINIfileItem $1 SYS effect_flag
    DelINIfileItem $1 SYS inactive_version
    DelINIfileItem $1 SYS inactive_upgrade_file
}

function set_install_type()
{
    INSTALL_TYPE_ARG=$1
    WORK_PATH_ARG=$2

    if [ "${INSTALL_TYPE_ARG}" == "Full" ]; then
        sed -i "s|is_enabled=.*|is_enabled=True|g" ${WORK_PATH_ARG}/software/edge_site/ha_handler/config/config.ini
        sed -i "s|is_enabled=.*|is_enabled=True|g" ${WORK_PATH_ARG}/software/edge_site/container_handler/config/config.ini
        sed -i "s|is_enabled=.*|is_enabled=True|g" ${WORK_PATH_ARG}/software/edge_site/postern/config/config.ini
    elif [ "${INSTALL_TYPE_ARG}" == "Typical" ]; then
        sed -i "s|is_enabled=.*|is_enabled=False|g" ${WORK_PATH_ARG}/software/edge_site/ha_handler/config/config.ini
        sed -i "s|is_enabled=.*|is_enabled=True|g" ${WORK_PATH_ARG}/software/edge_site/container_handler/config/config.ini
        sed -i "s|is_enabled=.*|is_enabled=True|g" ${WORK_PATH_ARG}/software/edge_site/postern/config/config.ini
    elif [ "${INSTALL_TYPE_ARG}" == "Simple" ]; then
        sed -i "s|is_enabled=.*|is_enabled=False|g" ${WORK_PATH_ARG}/software/edge_site/ha_handler/config/config.ini
        sed -i "s|is_enabled=.*|is_enabled=False|g" ${WORK_PATH_ARG}/software/edge_site/container_handler/config/config.ini
        sed -i "s|is_enabled=.*|is_enabled=False|g" ${WORK_PATH_ARG}/software/edge_site/postern/config/config.ini
    fi

    return 0
}

UPGRADE_BEGIN="upgrade_begin"
UPGRADE_BACKUP_FINISH="upgrade_backuped"
UPGRADE_DONE="upgrade_done"

set_upgrade_progress()
{
    WORK_PATH_ARG=$1
    step=$2

    if [ "$step" == "$UPGRADE_BEGIN" ]; then
        echo "task:upgrade" > ${WORK_PATH_ARG}/run_task
        echo "step:$UPGRADE_BEGIN" >> ${WORK_PATH_ARG}/run_task
        logger_Info "upgrade task process  $step"
        cat ${WORK_PATH_ARG}/run_task
    elif [ "$step" == "$UPGRADE_BACKUP_FINISH" ]; then
        echo "task:upgrade" > ${WORK_PATH_ARG}/run_task
        echo "step:$UPGRADE_BACKUP_FINISH" >> ${WORK_PATH_ARG}/run_task
        logger_Info "upgrade task process  $step"
        cat ${WORK_PATH_ARG}/run_task
    elif [ "$step" == "$UPGRADE_DONE" ]; then
        logger_Info "upgrade task process  $step rm file"
        if [ -f ${WORK_PATH_ARG}/run_task ];then
            rm ${WORK_PATH_ARG}/run_task
        fi
    else
        logger_Warn "arg err step:$step"
        return 1
    fi
}

WriteDevMgmtTypeToYaml(){
    YAMLFILE=$1
    PRODUCT_NAME=$2
    DevMgmtType="AtlasEdge"

    echo ${PRODUCT_NAME} | grep "TaiShan"
    if [ $? -eq 0 ]; then
        DevMgmtType="BMC"
    fi

    echo ${PRODUCT_NAME} | grep "Atlas 800"
    if [ $? -eq 0 ]; then
        DevMgmtType="BMC"
    fi

    echo ${PRODUCT_NAME} | grep "Atlas 500 Pro"
    if [ $? -eq 0 ]; then
        DevMgmtType="BMC"
    fi

    echo ${PRODUCT_NAME} | grep "G2500"
    if [ $? -eq 0 ]; then
        DevMgmtType="BMC"
    fi

    echo ${PRODUCT_NAME} | grep "2288H"
    if [ $? -eq 0 ]; then
        DevMgmtType="BMC"
    fi

    sed -i "s|devMgmtType:.*|devMgmtType: ${DevMgmtType}|g" ${YAMLFILE}
}

update_serial_num()
{
    WORK_CORE_CONFIG_FILE=$1
    ATLAS_EDGE_ELABLE_INFO="/run/elabel_info"

    if [ -f $ATLAS_EDGE_ELABLE_INFO ]; then
        serial_num=`cat $ATLAS_EDGE_ELABLE_INFO |grep "prd_serial_num" | awk '{print $2}'`
    fi

    check_command_exist dmidecode
    dmidecode_exist=$?

    # 序列号获取失败 从dmidecode中尝试获取
    if [ "${serial_num}" ==  "" -a $dmidecode_exist == 0 ]; then
        BMCType=`cat ${WORK_CORE_CONFIG_FILE} | grep devMgmtType | awk '{print $2}'`
        if [ "$BMCType" == "BMC" ]; then
            serial_num=`sudo dmidecode -t1 | grep "Serial Number:" | awk -F ":" '{print $2}' | awk '$1=$1'`
        else
            serial_num=`sudo dmidecode -t2 | grep "Serial Number:" | awk -F ":" '{print $2}' | awk '$1=$1'`
        fi
    fi

    if [ "${serial_num}" != "" -a "${serial_num}" != "Not Specified" -a "${serial_num}" != "Default string" ]; then
        sudo sed -i "s|serialNumber:.*|serialNumber: ${serial_num}|g" ${WORK_CORE_CONFIG_FILE}
    fi

}

function get_cert_dir()
{
    if [ -e /etc/redhat-release ] && [ ! -e /etc/lsb-release ]; then
        echo "/etc/pki/ca-trust/source/anchors"
    else
        echo "/usr/local/share/ca-certificates"
    fi
}

function update_interface_name() {
    core_yaml_path=$1
    networkInterfaces=$(ls /sys/class/net | grep -vE "denvid|docker0|lo")
    for networkInterface in ${networkInterfaces[@]}; do
        echo $(realpath /sys/class/net/$networkInterface) | grep -q "virtual"
        if [ $? -eq 0 ]; then
            continue
        fi
        ifconfig ${networkInterface} | grep -E "RUNNING|inet">/dev/null 2>&1
        if [ $? -eq 0 ]; then
            sed -i "s|interfaceName:.*|interfaceName: ${networkInterface} |g" ${core_yaml_path}
            break
        fi
    done
}

function bind_port_uid()
{
    CORE_YAML_PATH=$1

    HwUserName="HwHiAiUser"
    HwUserID=$(id -u ${HwUserName})

    CoreToSitePort=$(cat ${CORE_YAML_PATH} | grep mqttServerInternal | awk -F":" '{print $NF}' | awk -F" " '{print $1}')

    iptables -C OUTPUT -o lo -p tcp --dport ${CoreToSitePort} -j DROP > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        RestrictingPortOutput=$(iptables -I OUTPUT -o lo -p tcp --dport ${CoreToSitePort} -j DROP 2>&1)
        if [ $? -eq 0 ]; then
            logger_Info "succeeded in disabling all uid pass through mqtt_port"
        else
            logger_Warn "can not disable all uid pass through mqtt_port, reason: ${RestrictingPortOutput}"
            echo "Warning, can not disable all uid pass through mqtt_port, reason: ${RestrictingPortOutput}"
            return 1
        fi
    fi

    iptables -C OUTPUT -o lo -p tcp --dport ${CoreToSitePort} -m owner --uid-owner ${HwUserID} -j ACCEPT > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        AllowHwUidPassThroughPort=$(iptables -I OUTPUT -o lo -p tcp --dport ${CoreToSitePort} -m owner --uid-owner ${HwUserID} -j ACCEPT 2>&1)
        if [ $? -eq 0 ]; then
            logger_Info "succeeded in allowing the HwHiAiUser pass through mqtt_port"
        else
            logger_Warn "can not allow HwHiAiUser pass through mqtt_port, reason: ${AllowHwUidPassThroughPort}"
            echo "Warning, can not allow HwHiAiUser pass through mqtt_port, reason: ${AllowHwUidPassThroughPort}"
            iptables -D OUTPUT 1
            return 1
        fi
    fi

    iptables -C OUTPUT -o lo -p tcp --dport ${CoreToSitePort} -m owner --uid-owner 0 -j ACCEPT > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        AllowRootUidPassThrougPort=$(iptables -I OUTPUT -o lo -p tcp --dport ${CoreToSitePort} -m owner --uid-owner 0 -j ACCEPT 2>&1)
        if [ $? -eq 0 ]; then
            logger_Info "succeeded in allowing the HwHiAiUser pass through mqtt_port"
        else
            logger_Warn "can not allow Root pass through mqtt_port, reason: ${AllowRootUidPassThrougPort}"
            echo "Warning, can not allow Root pass through mqtt_port, reason: ${AllowRootUidPassThrougPort}"
            iptables -D OUTPUT 1
            iptables -D OUTPUT 1
        fi
    fi
}